<template>
  <div class="home-wrapper">
    <IndexHeader/>
    <Swiper :list="data.carousels"/>
    <CategoryList v-if="isLoading"/>
    <GoodList title="新品上线" :goods="data.newGoods" :loading="isLoading"/>
    <GoodList title="热门商品" :goods="data.hotGoods" :loading="isLoading"/>
    <GoodList title="最新推荐" :goods="data.recommendGoods" :loading="isLoading" class="pb-[100px]"/>
  </div>
</template>
<script setup lang="ts">
import {ref} from 'vue';

import getIndexListAPI, {type IGoodItem} from "@/api/home/getIndexListAPI";
import useLoading from "@/hooks/useLoading";
import {closeToast, showLoadingToast, showToast} from "vant";
import {SUCCESS_CODE} from "@/constants";

import {Swiper, type ISwipeItem} from "@/components/Swiper";
import CategoryList from "@/views/Home/components/CategoryList.vue";
import GoodList from "@/views/Home/components/GoodList.vue";
import IndexHeader from "@/views/Home/components/IndexHeader.vue";

const {isLoading, toggle} = useLoading();
const
    data = ref<{
      carousels: ISwipeItem[],
      newGoods: IGoodItem[],
      recommendGoods: IGoodItem[],
      hotGoods: IGoodItem[]
    }>(
        {
          carousels: [],
          newGoods: [],
          recommendGoods: [],
          hotGoods: []
        }
    )

const handleSearch = async () => {
  if (isLoading.value) {
    return
  }
  try {
    showLoadingToast({
      message: '加载中...',
      forbidClick: true
    });
    toggle(true)
    const response = await getIndexListAPI()
    if (response.code === SUCCESS_CODE) {
      const {carousels, newGoods, recommendGoods, hotGoods} = response.data;
      const carouselList = carousels.map(item => ({imageUrl: item.carouselUrl, redirectUrl: item.redirectUrl}));
      data.value = {
        newGoods,
        recommendGoods,
        hotGoods,
        carousels: carouselList
      }
    }
  } catch (e: any) {
    showToast(e.message);
  } finally {
    toggle(false)
    closeToast();
  }
}
handleSearch();
</script>